package com.hooya.fa.eu.biz.dao.manager;

import com.hooya.fa.eu.biz.dao.entity.Pk;
import com.hooya.fa.eu.biz.dao.entity.TempKcjlDaily;
import com.hooya.fa.eu.biz.dao.entity.TempPkpy;
import com.hooya.fa.eu.biz.dao.mapper.PkMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 盘库
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2025/2/5
 * @Version 1.1.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class PkManager {

    private final PkMapper pkMapper;

    private final GeneratorEntityManager generatorEntityManager;

    /**
     * 盘库
     *
     * @param date          日期
     * @param startDate     开始时间
     * @param inventoryList 库存
     * @return 盘亏盘盈list
     */
    public List<TempPkpy> closePosition(String date, String startDate, List<TempKcjlDaily> inventoryList) {
        List<TempPkpy> res = new LinkedList<>();
        //盘库数据(HY10319WH、SP36969补在进仓，其他的排除)
        List<String> excludeSkuList = Arrays.asList("FP10871DE", "RMA", "KE8965", "HY10319WH", "SP36969");
        List<Pk> evenUpList = pkMapper.getEvenUpList(date, excludeSkuList); // TODO - fa_eu.pk
        if (!CollectionUtils.isEmpty(evenUpList)) {
            Date now = new Date();
            evenUpList = evenUpList.stream().filter(l -> !(l.getSku().equals("ES10327DE-OR") && l.getPlace().equals("EU113")))
                    .collect(Collectors.toList());
            Map<String, TempKcjlDaily> kcMap = inventoryList.stream()
                    .collect(Collectors.toMap(l -> l.getCpbh() + "_" + l.getPlace() + "_" + l.getBelongs(), i -> i));
            for (Pk pk : evenUpList) {
                String key = pk.getSku() + "_" + pk.getPlace() + "_" + pk.getBelongs();
                TempKcjlDaily kc = kcMap.get(key);
                if (Objects.isNull(kc)) {
                    if (pk.getNum() > 0) {
                        inventoryList.add(generatorEntityManager
                                .genTempKcjlDaily(pk.getSku(), pk.getBelongs(), pk.getPlace(), pk.getNum(), date));
                        res.add(TempPkpy.builder().cpbh(pk.getSku()).sl(Math.negateExact(pk.getNum())).place(pk.getPlace())
                                .belongs(pk.getBelongs()).date(startDate).createTime(now).build());
                        continue;
                    } else {
                        throw new RuntimeException("库存数据不存在:" + pk);
                    }
                }
                res.add(TempPkpy.builder().cpbh(pk.getSku()).sl(Math.negateExact(pk.getNum()))
                        .place(pk.getPlace()).belongs(pk.getBelongs()).date(startDate).createTime(now).build());
                kc.setSl(kc.getSl() + pk.getNum());
            }
        } else {
            log.error("【" + date + "】不存在平仓数据，无需平仓");
        }
        return res;
    }
}
